package com.fengxu.gamescript.ui.float

import android.content.Context
import android.graphics.Color
import android.graphics.PixelFormat
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.text.TextUtils
import android.util.AttributeSet
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.BaseAdapter
import android.widget.FrameLayout
import android.widget.ListView
import android.widget.TextView
import androidx.core.view.isVisible
import com.fengxu.gamescript.R
import com.fengxu.gamescript.data.GlobalData
import com.fengxu.gamescript.jsengine.core.JsRuntime
import com.fengxu.gamescript.util.CommonUtils
import com.fengxu.gamescript.util.FloatUtils
import com.github.onlynight.library.lsearchview.LSearchView
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.xuexiang.xui.utils.DensityUtils
import com.xuexiang.xui.widget.toast.XToast
import com.yhao.floatwindow.FloatWindow
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.sdk27.coroutines.onEditorAction
import java.io.File

/**
 * 悬浮窗代码快捷选择栏
 */
class FloatScriptQuickSelect : FrameLayout {

    private val windowManager:WindowManager

    // 搜索组件
    private val mSearView:LSearchView by lazy {
        findViewById(R.id.flow_script_quick_searchView)
    }

    // 脚本列表组件
    private val mScriptListView:ListView by lazy {
        findViewById(R.id.flow_script_quick_list)
    }

    constructor(windowManager:WindowManager,context: Context) : super(context){
        this.windowManager = windowManager
        initView()
    }

    /**
     * 初始化控件
     */
    private fun initView(){
        backgroundColor = Color.parseColor("#33000000")
        padding =  DensityUtils.dp2px(40F)
        LayoutInflater.from(context).inflate(R.layout.flow_script_quickrun,this)
        this.onClick {  closeFloat() }
        findViewById<View>(R.id.flow_script_quick_close).onClick { closeFloat() }
        findViewById<View>(R.id.flow_script_quick_search).onClick {
            mSearView.isVisible = true
            mSearView.showWithAnim()
        }
        mSearView.searchEdit.run {
            singleLine = true
            imeOptions = EditorInfo.IME_ACTION_SEARCH
            textSize = 15F
        }
        // 设置搜索事件
        mSearView.searchEdit.onEditorAction { _, actionId, _ ->
            if(actionId == EditorInfo.IME_ACTION_SEARCH){
                searchScriptFile()
            }
        }
        mSearView.searchButton.onClick {
            searchScriptFile()
        }
        // 初始化脚本列表
        initScriptList()
    }

    /**
     * 初始化扫描到的脚本列表
     */
    private fun initScriptList(){
        mScriptListView.adapter = ScriptListAdapter()
        val smartRefreshLayout = findViewById<SmartRefreshLayout>(R.id.flow_script_quick_smartRefresh)
        smartRefreshLayout.setOnRefreshListener {
            (mScriptListView.adapter as ScriptListAdapter).refresh()
            it.finishRefresh()
        }
    }

    /**
     * 搜索搜索文件
     */
    private fun searchScriptFile(){
        mSearView.setSearching(true)
        (mScriptListView.adapter as ScriptListAdapter).filterFileByKeyword(mSearView.searchEdit.text.toString())
        mSearView.hideWithAnim()
        mSearView.setSearching(false)
    }

    /**
     * 脚本列表的适配器
     */
    private inner class ScriptListAdapter:BaseAdapter{

        // 扫描到的所有的脚本文件列表
        private val scriptList= mutableListOf<File>()

        // 真正使用做数据的文件列表
        private val datas = mutableListOf<File>()

        constructor(){
            scanScriptFiles()
            scriptList.forEach { datas.add(it) }
        }


        override fun getCount(): Int {
            return datas.size
        }

        override fun getItem(position: Int): Any {
            return datas[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            // 这里不使用convertView做缓存否则数据改变时无法及时改变
            return  TextView(context).apply {
                    textSize = 15F
                    text = datas[position].name
                    padding = DensityUtils.dp2px(10F)
                    textColorResource = R.color.skyblue
                    setBackgroundResource(R.drawable.script_quick_btn_bg)
                    ellipsize = TextUtils.TruncateAt.END
                    singleLine = true
                    layoutParams = LayoutParams(-1,-2)
                    onClick {
                        if(!GlobalData.getRunningScriptMap().containsKey(datas[position].name)){
                            JsRuntime(datas[position].name, context, datas[position].readText()).start()
                            CommonUtils.showDesktopToast(context,"运行成功", 1000)
                        }else{
                            CommonUtils.showDesktopToast(context,"该脚本已经在运行了，不可重复运行!")
                        }
                        closeFloat()
                    }
                }
        }

        /**
         * 扫描获取脚本的文件列表
         */
        private fun scanScriptFiles(){
            val file = File(GlobalData.MusicScriptFolderPath)
            file.listFiles().forEach {
                if(it.isFile && it.name.toLowerCase().endsWith(".js")){
                    scriptList.add(it)
                }
            }
        }

        /**
         * 刷新文件
         */
        fun refresh(){
            datas.clear()
            scriptList.forEach { datas.add(it) }
            notifyDataSetChanged()
        }

        /**
         * 过滤文件列表
         */
        fun filterFileByKeyword(kw: String){
            datas.clear()
            scriptList.forEach {
                if(Regex(kw,RegexOption.DOT_MATCHES_ALL).containsMatchIn(it.name)){
                    datas.add(it)
                }
            }
            notifyDataSetChanged()
        }

    }


    /**
     * 显示至悬浮窗
     */
    fun showFloat() {
        val lp = FloatUtils.getDefaultFloatParams()
        val screenMetrics = DensityUtils.getScreenMetrics(true)
        lp.width = screenMetrics.widthPixels
        lp.height = screenMetrics.heightPixels
        windowManager.addView(this, lp)
    }

    /**
     * 关闭该悬浮窗
     */
    fun closeFloat(){
        windowManager.removeView(this)
    }
}